package com.xbk.seckill.dubbo.interfaces.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.MDC;

/**
 * @author xiexu
 * @date 2025/5/13 08:43
 */
@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER}, value = "tracing")
public class DubboTraceFilter implements Filter {

    /**
     * TraceId key
     */
    private static final String TRACE_ID = "traceId";
    /**
     * SpanId key
     */
    private static final String SPAN_ID = "spanId";

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        // 获取dubbo上下文中的traceId和spanId
        String traceId = RpcContext.getContext().getAttachment(TRACE_ID);
        String spanId = RpcContext.getContext().getAttachment(SPAN_ID);
        if (StringUtils.isBlank(traceId)) {
            // customer设置traceId到dubbo的上下文
            RpcContext.getContext().setAttachment(TRACE_ID, MDC.get(TRACE_ID));
        } else {
            // provider设置traceId到日志的上下文
            MDC.put(TRACE_ID, traceId);
        }
        if (StringUtils.isBlank(spanId)) {
            // customer设置spanId到dubbo的上下文
            RpcContext.getContext().setAttachment(SPAN_ID, MDC.get(SPAN_ID));
        } else {
            // provider设置spanId到日志的上下文
            MDC.put(SPAN_ID, spanId);
        }
        return invoker.invoke(invocation);
    }

}
